<template>
  <view :class="theme">

    <view v-if="tabs.list.length > 1" class="mt-30 flex-1 items-center">
      <uv-subsection @change="tabs.current = $event;" :list="tabs.list" key-name="name"
        :customStyle="{ width: '420rpx', height: `72rpx` }" :current="tabs.current" font-size="28"
        :active-color="$config.COLOR_PRIMARY" :inactive-color="$config.COLOR_BASE" mode="button" />
    </view>

    <view class="m-30">
      <view class="relative items-center">
        <uv-image radius="20" width="646" height="700" :src="include(poster.invite_poster?.[0])" />
      </view>

      <view class="mt-[-30rpx] relative self-center">
        <uv-image width="690" height="208" src="/static/img/share/1.png" />

        <view v-if="poster[tabs.list[tabs.current].field]"
          class="absolute left-60 right-50 top-30 bottom-30 flex-row items-center justify-between">
          <view>
            <l-painter :css="`width: 180rpx; height: 180rpx; background-color: #fff; border-radius: 16rpx;`"
              isCanvasToTempFilePath>
              <l-painter-qrcode css="width: 150rpx; height: 150rpx; margin: 15rpx;" :text="qrCodeText" />
            </l-painter>
          </view>

          <view class="color-inverse fw-bold">
            <text class="text-50">{{ poster[tabs.list[tabs.current].field] }}</text>
            <text class="mt-24">扫一扫立即加入龙之大陆</text>
          </view>
        </view>
      </view>
    </view>
    <button @click="saveImage" hover-class="op-[0.6]"
      class="bg-main text-36 color-inverse fw-700 b-rounded-24 lh-100 m-90">保存图片</button>

    <l-painter ref="painter" useCORS custom-style="position: fixed; top: 0; left: -100%;" />
    <!-- <l-painter ref="painter" useCORS /> -->
  </view>
</template>

<script lang="ts" setup>
import { useMapState } from "@/common/libs/store";
import { debounce, getClient } from "@/common/libs/utils";
import { onLoad } from "@dcloudio/uni-app";
import { ref, reactive, computed } from "vue";

const { theme } = useMapState(["theme"]);
const { $config = {} } = getApp().globalData || {};
const poster = reactive({
  invite_poster: [$config.URL_STATIC + "/img/poster.png"],
  code: "",
  px_code: "",
});
const tabs = reactive({
  list: [
    { name: "邀请码", field: "code" },
    { name: "排线码", field: "px_code" },
  ] as { name: string; field: "code" | "px_code" }[],
  current: 0
});
const painter = ref<any>(null);

const qrCodeText = computed(
  () => `${$config.URL_ASSETS + $config.ROUTE_PREFIX}?timestamp=${Date.now()}#/pages/client/auth/register?code=${poster[tabs.list[tabs.current].field] || '-'}`
);

onLoad(() => {
  uni.request({
    url: $config.API_USER_INFO_GET,
    success({ data }: any) {
      poster.code = data.code;
      poster.px_code = data.px_code || "";
      uni.hideToast();
    },
  });
});

const saveImage = debounce(async () => {
  await renderPoster();
  uni.showToast({ mask: true, icon: "loading" });
  painter.value.canvasToTempFilePath({
    fileType: "png",
    quality: 100,
    success: ({ tempFilePath }: any) => {
      switch (getClient()) {
        case 1:
        case 2:
        case 3:
        case 4:
          const arr = tempFilePath.split(',');
          const bytes = window.atob(arr[1]);
          const ab = new ArrayBuffer(bytes.length);
          const ia = new Uint8Array(ab);
          for (let i = 0; i < bytes.length; i++) {
            ia[i] = bytes.charCodeAt(i);
          }
          const blob = new Blob([ab], { type: `application/octet-stream` });
          const url = URL.createObjectURL(blob);
          const a = document.createElement('a');
          a.href = url;
          a.download = `poster.png`;
          a.click();
          URL.revokeObjectURL(url);
          break;
        case 5:
        case 6:
        case 7:
        case 8:
          uni.showToast({ mask: true, icon: "loading" });
          uni.saveImageToPhotosAlbum({
            filePath: tempFilePath,
            success: res => {
              uni.showToast({ title: "图片已保存至相册", icon: "none" });
            }
          });
          break;
        case 9:
          // uni.showToast({ title: "图片已保存至相册", icon: "none" });
          break;
        case 10:
          // uni.showToast({ title: "图片已保存至相册", icon: "none" });
          break;
        default:
          break;
      }
      uni.hideToast();
    }
  });
});

const renderPoster = async () => {
  uni.showToast({ mask: true, icon: "loading" });
  await painter.value.render({
    css: {
      width: "690rpx",
      height: "884rpx",
      position: 'relative'
    },
    views: [
      {
        type: 'image',
        css: {
          position: "absolute",
          width: "646rpx",
          height: "700rpx",
          objectFit: "cover",
          borderRadius: "20rpx",
          left: "22rpx",
        },
        src: poster.invite_poster?.[0]
      },
      {
        type: "view",
        css: {
          position: 'absolute',
          bottom: 0,
          width: '100%'
        },
        views: [
          {
            type: 'image',
            css: {
              width: "100%",
              height: "208rpx",
              objectFit: "cover",
            },
            src: "/static/img/share/1.png"
          },
          {
            type: "view",
            css: {
              position: "absolute",
              width: '180rpx',
              height: '180rpx',
              backgroundColor: '#fff',
              borderRadius: '16rpx',
              left: "60rpx",
              top: "14rpx",
            },
            views: [
              {
                type: "qrcode",
                text: qrCodeText.value,
                css: {
                  width: '150rpx',
                  height: '150rpx',
                  margin: '15rpx',
                }
              }
            ]
          },
          {
            type: "view",
            css: {
              position: "absolute",
              width: '280rpx',
              height: '64rpx',
              right: "30rpx",
              top: "46rpx",
            },
            views: [
              {
                type: "text",
                text: poster[tabs.list[tabs.current].field],
                css: {
                  fontSize: "50rpx",
                  fontWeight: "bold",
                  color: "#0c003b",
                }
              },
              {
                type: "text",
                text: "扫一扫立即加入龙之大陆",
                css: {
                  fontSize: "24rpx",
                  fontWeight: "bold",
                  color: "#0c003b",
                }
              }
            ]
          },
        ]
      },

    ]
  });
  uni.hideToast();
}

</script>

<style lang="scss" scoped>
// scss
</style>